<template>
    <div>
        <el-button class="width-100" 
            :loading="load" 
            :disabled="disabled" 
            @click="sendCapatch2Email" plain>
            {{ label }}
        </el-button>
    </div>
</template>

<script>
import * as utils from "@/utils";
import {sendCaptcha2Email} from "@/api/captcha";
export default {
    name:'EmailCaptchaButton',
    props:{
        btnLabel: {
            type: String, //接收类型
            required: true, //必填
            default: '' //默认值
        },
        btnEmail: {
            type: String, //接收类型
            required: true, //必填
            default: '' //默认值
        }
    },
    data(){
        return{
            load: false,
            label: this.btnLabel,
            email: this.btnEmail,
            disabled: false
        }
    },
    computed: {},
    components: {},
    methods: {
        sendCapatch2Email(){
            console.log(this.email);
            if(utils.isEmpty(this.email)){
                this.$message.error(this.$t('email_captcha_button.email_is_not_blank'));
                return;
            }
            this.load=true;
            sendCaptcha2Email({email: this.email}).then(res=>{
                const {code, msg, data} = res;
                if(code===200){
                    let{sessionId,timeout,createTime} = data;
                    this.$emit('sendCaptchaSuccess', sessionId);
                    this.countDown(timeout,createTime);
                    this.$message.success(this.$t('email_captcha_button.send_success'));
                }else {
                    this.$message.error(msg);
                    this.load=false;
                }
            });
        },
        countDown(timeout, createTime){//倒计时重发验证码
            if(!timeout) {
                this.load=false;
                return;
            }
            let now = new Date().getTime();
            let sendtime = now;
            if(createTime) sendtime = new Date(createTime).getTime();
            let clock = Math.floor(timeout-(now-sendtime)/1000);
            const _this = this;
            const fader=setInterval(function(){
                if(clock===1) {
                    _this.load = true;
                    _this.label = _this.btnLabel;
                    clearInterval(fader);
                }else {
                    _this.label = (clock--)+_this.$t('email_captcha_button.resend_text');
                }
            }, 1000);
        }
    },
    mounted() {},
    watch: {//父组件修改btnLabel时，监听
        btnLabel() {//这里的方法名与props中的相同
            if(!this.load) this.label = this.btnLabel;
        },
        btnEmail() {
            this.email = this.btnEmail;
        }
    }
}

</script>
<style scoped>
</style>